//
//  NSFileManager+WLExtension.m
//  xiacai
//
//  Created by 专注 on 2018/1/11.
//  Copyright © 2018年 TBS. All rights reserved.
//

#import "NSFileManager+WLExtension.h"

@implementation NSFileManager (WLExtension)

/**
 路径是否存在
 
 @param path 路径
 @return YES 存在  NO 不存在
 */
+ (BOOL)wl_isPathExist:(NSString *)path{
    return [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:nil];
}

/**
 创建 或者获取 文件夹路径

 @param folderName 文件夹名称
 @return 文件夹路径
 */
+ (NSString *_Nullable)wl_createFolderName:(NSString *_Nullable)folderName{
    NSString *path = [NSFileManager cachePath:folderName];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:nil]) {
        NSError *error = nil;
        [[NSFileManager defaultManager] createDirectoryAtPath:path
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:&error];
        if (error) {NSLog(@"创建缓存目录错误：%@",error); return nil;}
    }
    NSLog(@"目录路径：%@",path);
    return path;
}




/** 删除文件或者文件夹 */
+(BOOL)wl_deleteFilePath:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager removeItemAtPath:path error:nil];
}


/**
  复制文件到指定文件夹
 
 @param fromPath 需要移动的文件路径（包含文件名）
 @param toFromPath 移动到的目标路径（不需要饱含最后一层路径）
 @return 文件夹路径
 */
+ (NSString *)wl_copyToFilePath:(NSString *_Nullable)fromPath toFromPath:(NSString *_Nullable)toFromPath{
    NSLog(@"from:%@--to:%@",fromPath,toFromPath);

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fromPath]){
        fromPath = [fromPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    if (![fileManager fileExistsAtPath:fromPath]) {
        NSLog(@"需移动文件或者目录不存在");
        return nil;
    }
    NSString *toPath = [self wl_newPathToFromPath:toFromPath fileNmae:[fromPath lastPathComponent] nameCount:0];
    NSError *error = nil;
    BOOL is = [fileManager copyItemAtPath:fromPath toPath:toPath error:&error];
    if (is){
        return toPath;
    }
    return nil;
}

/** 移动文件根目录 */
+ (NSString *)wl_moveToLocalFilePath:(NSString *)fromPath{
    return [self wl_copyToFilePath:fromPath toFromPath:[self wl_createFolderName:nil]];
}

/**
  移动文件到指定文件夹
 
 @param fromPath 需要移动的文件路径（包含文件名）
 @param toFromPath 移动到的目标路径（不需要饱含最后一层路径）
 @return 文件夹路径
 */
+ (NSString *)wl_moveToFilePath:(NSString *_Nullable)fromPath toFromPath:(NSString *_Nullable)toFromPath{
    NSLog(@"from:%@--to:%@",fromPath,toFromPath);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fromPath]){
        fromPath = [fromPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    if (![fileManager fileExistsAtPath:fromPath]) {
        NSLog(@"需移动文件或者目录不存在");
        return nil;
    }
    NSString *toPath = [self wl_newPathToFromPath:toFromPath fileNmae:[fromPath lastPathComponent] nameCount:0];
    NSError *error = nil;
    BOOL is  = [fileManager moveItemAtPath:fromPath toPath:toPath error:&error];
    if (is){
        return toPath;
    }
    return nil;
}

/** 重命名文件 */
+ (NSString *)wl_renameFilePath:(NSString *)fromPath toName:(NSString *)name{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fromPath]) {
        NSLog(@"需要重命名文件不存在");
        return nil;
    }
    NSString *toPath = [[fromPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:name];
    if ([fileManager fileExistsAtPath:toPath]) {
        NSLog(@"目标文件或者目录已存在");
        return nil;
    }
    NSString *headerComponent = [toPath stringByDeletingLastPathComponent];
    if ([self wl_creatFileWithPath:headerComponent]) {
        if ([fileManager moveItemAtPath:fromPath toPath:toPath error:nil]){
            return toPath;
        }
    }
    return nil;
}

//创建文件
+ (BOOL)wl_creatFileWithPath:(NSString *)filePath
{
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL temp = [fileManager fileExistsAtPath:filePath];
    if (temp) {
        return YES;
    }
    NSError *error;
    //stringByDeletingLastPathComponent:删除最后一个路径节点
    NSString *dirPath = [filePath stringByDeletingLastPathComponent];
    isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
    if (error) {
        NSLog(@"creat File Failed. errorInfo:%@",error);
    }
    if (!isSuccess) {
        return isSuccess;
    }
    isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    return isSuccess;
}




/** 清除 */
+ (BOOL)clearAllCache_wl{
    NSString *directoryPath = [NSFileManager cachePath:nil];
    return [[NSFileManager defaultManager] removeItemAtPath:directoryPath error:nil];
}

+ (NSString *)cachePath:(NSString *)pathName{
    NSString *cachePath =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES).firstObject;
    if (pathName) {
        return [[cachePath stringByAppendingPathComponent:@"WLCache"] stringByAppendingPathComponent:pathName];
    } else {
        return [cachePath stringByAppendingPathComponent:@"WLCache"];
    }
}



/** 文件防重名 */
+(NSString *)wl_newPathToFromPath:(NSString *_Nullable)toFromPath fileNmae:(NSString *)fileName nameCount:(NSInteger)nameCount{
    NSString *setFileName = fileName;
    if (nameCount >= 1){
        NSArray *ar = [fileName componentsSeparatedByString:@"."];
        if (ar.count >= 2){
            setFileName = [NSString stringWithFormat:@"%@(%ld).%@",[ar firstObject],nameCount,[ar lastObject]];
        } else {
            setFileName = [NSString stringWithFormat:@"%@%ld",fileName,nameCount];
        }
    }
    NSString *toPath = [toFromPath stringByAppendingPathComponent:setFileName];
    while ([[NSFileManager defaultManager] fileExistsAtPath:toPath]) {
        return [NSFileManager wl_newPathToFromPath:toFromPath fileNmae:fileName nameCount:nameCount + 1];
    }
    return toPath;
}
@end
